<template>
  <div class="el-login">
    <el-card shadow="hover" header="登录" style="width: 500px; height: 300px">
      <el-form
        :model="ruleForm"
        status-icon
        :rules="rules"
        ref="ruleForm"
        label-width="100px"
        class="demo-ruleForm"
      >
        <el-form-item label="用户名" prop="username">
          <el-input v-model="ruleForm.username"></el-input>
        </el-form-item>

        <el-form-item label="密码" prop="password">
          <el-input
            type="password"
            v-model="ruleForm.password"
            autocomplete="off"
          ></el-input>
        </el-form-item>

        <el-form-item style="margin-top: 2rem">
          <el-button type="primary" @click="submitForm('ruleForm')"
            >登录</el-button
          >
          <el-button style="margin-left: 200px" @click="resetForm('ruleForm')"
            >重置</el-button
          >
        </el-form-item>
      </el-form>
    </el-card>
  </div>
</template>

<script>
import { login } from "../api/users";
import { setToken } from "../uitls/auth";
export default {
  data() {
    return {
      ruleForm: {
        password: "",
        username: "",
      },
      rules: {
        password: [{ required: true, message: "请输入密码", trigger: "blur" }],

        username: [
          { required: true, message: "请输入用户名", trigger: "blur" },
        ],
      },
    };
  },
  methods: {
    submitForm(formName) {
      this.$refs[formName].validate((valid) => {
        if (valid) {
          login(this.ruleForm)
            .then(({ data }) => {
              let res = data;

              console.log(res);
              if (res.code === 1000) {
                // localStorage.setItem("accessToken", res.data.token);
                // localStorage.setItem("refreshToken", res.data.refreshToken);
                setToken(res.data.token,res.data.refreshToken);
                this.$router.push('/doecharts').catch(()=>{})
              } else {
                this.$message({ type: "warning", message: res.msg ,showClose: true});
              }
            })
            .catch((err) => {
              console.log(err);
            });
        } else {
          console.log("error submit!!");
          return false;
        }
      });
    },
    resetForm(formName) {
      this.$refs[formName].resetFields();
    },
  },
};
</script>

<style>
.el-login {
  display: flex;
  margin-left: 25%;
  margin-top: 10%;
}
.el-login .el-card__header {
  display: flex;
  align-items: center;
  justify-content: center;
  font-size: 20px;
}
.demo-ruleForm {
  margin-top: 1rem;
  margin-right: 2rem;
}
</style>